package com.cl.it.spider;

import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.SearchContext;
import org.openqa.selenium.WebElement;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

public interface NextPageSpider {

    default int loopStart() {
        return 0;
    }

    default boolean has(SearchContext context, By by) {
        try {
            List<WebElement> elements = context.findElements(by);
            return (elements == null || elements.size() == 0) ? false : true;
        } catch (NoSuchElementException e) {
            return false;
        }
    }

    default boolean has(SearchContext context, String pageCssSelector) {
        try {
            List<WebElement> elements = context.findElements(By.cssSelector(pageCssSelector));
            return (elements == null || elements.size() == 0) ? false : true;
        } catch (NoSuchElementException e) {
            return false;
        }
    }

    default List<Object> each(SearchContext context, String listCssSelector, String paginationSelector) {
        boolean hasNext;
        List<Object> objs = new ArrayList<>();
        do {
            if (!has(context, listCssSelector)) {
                return null;
            }
            List<WebElement> elements = context.findElements(By.cssSelector(listCssSelector));
            if (CollectionUtils.isEmpty(elements)) {
                return null;
            }
            for (int i = loopStart(); i < elements.size(); i++) {
                WebElement element = elements.get(i);
                Object obj = one(element);
                objs.add(obj);
            }
            WebElement pagination = null;
            if (has(context, paginationSelector)) {
                pagination = context.findElement(By.cssSelector(paginationSelector));
            }
            hasNext = next(pagination);
            try {
                Thread.sleep(1000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } while (hasNext);
        return objs;
    }


    Object one(WebElement element);

    boolean next(SearchContext context);
}
